package cn.huangsm.advance.optimisticlock.controller;

import cn.huangsm.advance.optimisticlock.bean.User;
import cn.huangsm.advance.optimisticlock.mapper.UserMapper;
import cn.huangsm.advance.ratelimiter.RateLimitAspect;
import cn.huangsm.advance.ratelimiter2.AccessRateLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author huang
 * @PACKAGE_NAME cn.huangsm.advance.optimisticlock.controller
 * @PROJECT_NAME advance-code
 * @date 2019/1/10
 */
@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/test/{id}")
    @AccessRateLimiter(limitNum = 100.0)
    public void test(@PathVariable("id") Integer id) {
        User user = userMapper.selectById(id);
        user.setVersion(1);
        userMapper.updateById(user);
    }

    @GetMapping("/find/{id}")
    public User find(@PathVariable("id") Integer id) {
        return userMapper.selectById(id);
    }

    /**
     * 测试乐观锁
     */
    @GetMapping("/CAS")
    public void cas() {
        /**
         * 根据相同的id查询出商品信息,赋给2个对象
         */
        User user1 = userMapper.selectById(1);
        User user2 = userMapper.selectById(1);
        /**
         * 打印相同商品信息
         */
        System.out.println(user1);
        System.out.println(user2);
        /**
         * 更新商品信息1
         */
        user1.setName("王");
        int updateResult1 = userMapper.updateUserUseCAS(user1);
        System.out.println("修改商品信息1" + (updateResult1 == 1 ? "成功" : "失败"));
        /**
         * 更新商品信息2
         */
        user1.setName("王");
        int updateResult2 = userMapper.updateUserUseCAS(user2);
        System.out.println("修改商品信息2" + (updateResult2 == 1 ? "成功" : "失败"));
    }

    @Autowired
    private UserService userService;

    @GetMapping("/mpCas/{id}")
    public void mpCas(@PathVariable("id")Integer id) {
        User user = userService.getById(id);
        user.setAge(21);
        if (userService.updateById(user)) {
            System.out.println("Update successfully");
        } else {
            System.out.println("Update failed due to modified by others");
        }
    }
    /**
     * 分页查询
     */
    @GetMapping("/list")
    public List<User> pageList(){
        return userService.findPage();
    }
}
